package qeb.handheldmedical.instruction;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import qeb.handheldmedical.R;
import qeb.handheldmedical.adapter.CheckInstructionItemAdapter;
import qeb.handheldmedical.adapter.SlideListView;
import qeb.handheldmedical.dialog.MultiDialog;
import qeb.handheldmedical.helper.WSHelper;
import qeb.handheldmedical.model.InPatient;
import qeb.handheldmedical.model.MInstruction;
import qeb.handheldmedical.model.User;

/**
 * @author 作者(dugaoyi) E-mail:dugaoyi@163.com
 * @version 创建时间：2017年2月22日 下午1:53:00
 * @declaration
 */
public class CheckInstruction extends Activity {

    private InPatient pi;
    private User usr;
    private Button btn_title_back, btn_title_right;
    private Button btn_wzx, btn_yzx;
    private Button btn_jp, btn_kf;
    public static final String BAR_READ_ACTION = "SYSTEM_BAR_READ";// 条码广播
    public static final String RFID_READ_ACTION = "SYSTEM_RFID_READ";// RFID广播

    // honeywell
    private final static String TAG = "ScanResultReceiver";
    private static final String INTENT_ACTION_SCAN_RESULT = "com.honeywell.tools.action.scan_result";
    public static final String NLSCAN_SCANNER = "nlscan.action.SCANNER_RESULT";// 新大陆机型
    private static final String SCANACTION = "com.android.server.scannerservice.broadcastxhyy";// 小码哥
    private static final String Neusoft = "com.neusoft.action.scanner.read";// 东软
    public String action;// 扫描
    private BroadcastReceiver checkInstructionReciever;
    private List<MInstruction> yzlist = new ArrayList<MInstruction>();
    private Button btn_chkyzcx, btn_yzall;
    private EditText tv_Date;
    private TextView tv_title, tv_Syzs, tv_Yzzxts, tv_Yzsyts;

    private final Handler mHandler = new MyHandler(this);
    private String initStartDateTime;// 初始化开始时间
    private JSONArray jsonArray;
    private SlideListView slvYz;
    private CheckInstructionItemAdapter adapter;
    /**
     * 0全部 1 已执行 2 未执行 3静配 4口服
     */
    private String strType = "0"; // 0=全部，1=静配输液，2=口服 3=检验 4=其他
    //    private String strState = "0";// 0=未执行，1=已执行,2=最后输液,空=全部
    private Resources resources;
    private Drawable btnDrawableGold;
    private Drawable btnDrawableGreen;
    private String strJlxh = "";// 条形码（记录序号）
    private String strPbh = "";// 判别号
    private String strYzmc = "";
    private MultiDialog mDialog;
    private String strLy = "";// 1病人信息切换过来，2是病人列表扫描过来
    private String zxYzJlxh = "";// 执行医嘱记录序号
    private Button btn_zxz;
    private TextView tvMsg;

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.check_instruction);
        pi = (InPatient) getIntent().getSerializableExtra("patientinfo");
        usr = (User) getIntent().getSerializableExtra("userinfo");
        strLy = getIntent().getStringExtra("ly");
        initView();
        if (pi != null && usr != null) {
            LogListActivity.logList.add("携带进来的患者信息 -> " + pi.toString());
            LogListActivity.logList.add("携带进来的用户信息 -> " + usr.toString());
        }

        initBarReciever();
    }


    public static String getJson(String fileName,Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 初始化加载界面
     */
    private void initView() {
        // TODO Auto-generated method stub

        tv_Syzs = (TextView) findViewById(R.id.tv_Syzs);
        tv_Syzs.setText("0");
        tv_Yzzxts = (TextView) findViewById(R.id.tv_Yzzxts);
        tv_Yzzxts.setText("0");
        tv_Yzsyts = (TextView) findViewById(R.id.tv_Yzsyts);
        tv_Yzsyts.setText("0");
        btn_title_back = (Button) findViewById(R.id.btn_title_back);
        btn_title_back.setOnClickListener(MyOnClickListener);
        btn_title_right = (Button) findViewById(R.id.btn_title_right);
        btn_title_right.setOnClickListener(MyOnClickListener);
        tv_title = (TextView) findViewById(R.id.tv_top_title);
        tv_title.setText(pi.XM);
        resources = this.getResources();
        btnDrawableGold = resources.getDrawable(R.drawable.background_gold);
        btnDrawableGreen = resources.getDrawable(R.drawable.background_green);
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        initStartDateTime = sDateFormat.format(new java.util.Date());
        tv_Date = (EditText) findViewById(R.id.tv_Date);
        tv_Date.setOnClickListener(MyOnClickListener);
        tv_Date.setText(initStartDateTime);
        btn_chkyzcx = (Button) findViewById(R.id.btn_chkyzcx);
        btn_chkyzcx.setOnClickListener(MyOnClickListener);
        slvYz = (SlideListView) findViewById(R.id.slvYz);
        tvMsg = findViewById(R.id.tvMsg);
        btn_yzx = (Button) findViewById(R.id.btn_yzx);
        btn_yzx.setOnClickListener(MyOnClickListener);

        btn_zxz = (Button) findViewById(R.id.btn_zxz);
        btn_zxz.setOnClickListener(MyOnClickListener);

        btn_jp = (Button) findViewById(R.id.btn_jp);
        btn_jp.setOnClickListener(MyOnClickListener);

        btn_kf = (Button) findViewById(R.id.btn_kf);
        btn_kf.setOnClickListener(MyOnClickListener);
        btn_yzall = (Button) findViewById(R.id.btn_yzall);
        btn_yzall.setOnClickListener(MyOnClickListener);

        btn_wzx = (Button) findViewById(R.id.btn_wzx);
        btn_wzx.setOnClickListener(MyOnClickListener);
        findViewById(R.id.btLog).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CheckInstruction.this, LogListActivity.class);
                startActivity(intent);
            }
        });

        btn_chkyzcx.performClick();

    }

    private void ThreadBand() {
        mDialog = new MultiDialog(CheckInstruction.this,
                MultiDialog.DialogType.WAITING);
        mDialog.setMessage("正在加载，请稍候......");
        mDialog.show();
        new Thread() {

            @Override
            public void run() {
                try {
                    mHandler.sendEmptyMessage(1);
                    mDialog.cancel();
                } catch (Exception e) {
                    // TODO: handle exception
                    // Log.v("LineExam", e.toString());
                }
            }
        }.start();

    }

    private OnClickListener MyOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            //0全部 1 已执行 2 未执行 3静配 4口服
            switch (v.getId()) {
                case R.id.btn_title_back:
                    CheckInstruction.this.finish();
                    break;
                case R.id.tv_Date:
//                    DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
//                            CheckInstruction.this, tv_Date.getText().toString());
//                    dateTimePicKDialog.dateDialog(tv_Date);
                    break;
                case R.id.btn_chkyzcx:
                    ThreadBand();
                    break;

                case R.id.btn_wzx:
                    strType = "2";
                    btn_wzx.setBackground(btnDrawableGold);
                    btn_yzx.setBackground(btnDrawableGreen);
                    btn_zxz.setBackground(btnDrawableGreen);
                    ThreadBand();
                    break;
                case R.id.btn_yzx:
                    strType = "1";
                    btn_wzx.setBackground(btnDrawableGreen);
                    btn_yzx.setBackground(btnDrawableGold);
                    btn_zxz.setBackground(btnDrawableGreen);
                    ThreadBand();
                    break;
                case R.id.btn_yzall:
                    strType = "0";
                    tvMsg.setText("总数量");
                    btn_yzall.setBackground(btnDrawableGold);
                    btn_jp.setBackground(btnDrawableGreen);
                    btn_kf.setBackground(btnDrawableGreen);
                    ThreadBand();
                    break;
                case R.id.btn_zxz:
                    strType = "5";
                    btn_zxz.setBackground(btnDrawableGold);
                    btn_wzx.setBackground(btnDrawableGreen);
                    btn_yzx.setBackground(btnDrawableGreen);
                    ThreadBand();
                    break;
                case R.id.btn_jp:
                    strType = "3";
                    tvMsg.setText("输液总数量");
                    btn_yzall.setBackground(btnDrawableGreen);
                    btn_jp.setBackground(btnDrawableGold);
                    btn_kf.setBackground(btnDrawableGreen);
                    ThreadBand();
                    break;
                case R.id.btn_kf:
                    strType = "4";
                    tvMsg.setText("口服总数量");
                    btn_yzall.setBackground(btnDrawableGreen);
                    btn_jp.setBackground(btnDrawableGreen);
                    btn_kf.setBackground(btnDrawableGold);
                    ThreadBand();
                    break;
                case R.id.btn_title_right:
                    ThreadBand();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 读取执行医嘱数据
     */
    private void readInstruction() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("emrzyxh", !TextUtils.isEmpty(pi.BAH) ? pi.BAH : pi.HISZYXH);
        map.put("zxsj", tv_Date.getText().toString());
        map.put("type", strType);// 0=全部，1=静配输液，2=口服 3=检验 4=其他
//        LogListActivity.logList.add("请求PDADocOrderInfoView参数-> emrzyxh:" + pi.BAH + " Zxsj:" + tv_Date.getText().toString() + " type:" + strType + "");
        jsonArray = WSHelper.getAdviceList("PDADocOrderInfoView", map);
        if (jsonArray != null) {
//            LogListActivity.logList.add("请求PDADocOrderInfoView返回: " + jsonArray.toString());
        }

    }
    // 查询病人列表
    private JSONArray readPiList() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("deptID", usr.BQID);
        map.put("userID", usr.DID);
        JSONArray patientJsonArray = WSHelper.getWebserviceFun(
                "GetPatientList4PDA", map);
        return patientJsonArray;
    }

    private void initBarReciever() {
        checkInstructionReciever = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                action = intent.getAction();
                Log.d("scan", "Checkinstruction");

                String BAR_value = "";
                String STATE_value = "ok";
                if (action.equals(BAR_READ_ACTION)) {
                    BAR_value = intent.getStringExtra("BAR_VALUE");
                } else if (action.equals(RFID_READ_ACTION)) {
                    BAR_value = intent.getStringExtra("RFID_VALUE");
                } else if (action.equals(INTENT_ACTION_SCAN_RESULT)) {

                    if (intent.hasExtra("decode_rslt")) {
                        BAR_value = intent.getStringExtra("decode_rslt");
                    }

                } else if (action.equals(SCANACTION)) {
                    BAR_value = intent.getStringExtra("scannerdata")
                            .replaceAll("\r|\n", "");
                } else if (action.equals(Neusoft)) {
                    BAR_value = intent.getStringExtra("scanner_value")
                            .replaceAll("\r|\n", "");
                } else if (action.equals(NLSCAN_SCANNER)) {
                    STATE_value = intent.getStringExtra("SCAN_STATE");
                    BAR_value = TextUtils.isEmpty(intent.getStringExtra("SCAN_BARCODE1")) ? intent.getStringExtra("SCAN_BARCODE2") : intent.getStringExtra("SCAN_BARCODE1");
                    BAR_value = BAR_value.replaceAll("\r|\n", "");
                }


                if (!BAR_value.equals("ERROR") || STATE_value.equals("ok")) {// 扫描出错
                    String lastStr = BAR_value.substring(
                            BAR_value.length() - 1, BAR_value.length());// 最后一个字符
                    if (lastStr.equals("|") && strLy.equals("2")) {
                        // 如果病人是从病人列表切换过来可以扫描病人二维码
                        String[] values = BAR_value.split("\\|");
                        String zyxh = values[1];
//                        LogListActivity.logList.add("zyxh => "+ zyxh +"");
                        JSONArray piList = readPiList();
                        if (piList != null) {

                            try {
                                boolean IsUpdatePi = false;
                                for (int i = 0; i < piList.length(); i++) {
                                    JSONObject piJsonObject = piList
                                            .getJSONObject(i);
                                    String strPatientsJson = piJsonObject
                                            .getString("PATIENTS");

                                    JSONArray patietnsArray = new JSONArray(
                                            strPatientsJson);
                                    for (int k = 0; k < patietnsArray
                                            .length(); k++) {
                                        JSONObject piInfoObject = patietnsArray
                                                .getJSONObject(k);
//                                        LogListActivity.logList.add( "遍历的第"+k+"个病人数据 =>"+ piInfoObject.toString() +"");
//                                        LogListActivity.logList.add( "遍历的第"+k+"个病人住院序号 =>"+ piInfoObject.getString("ZYXH"));
                                        // 查找病人是否在当前病区
                                        if (piInfoObject.getString("ZYXH")
                                                .equals(zyxh)) {
                                            IsUpdatePi = true;
                                            pi = new InPatient();
                                            pi.getValue(piInfoObject);
                                            tv_title.setText(pi.XM);
                                            btn_chkyzcx.performClick();
                                            break;
                                        }
                                    }

                                }
                                if (!IsUpdatePi) {
//                                    Toast tt = Toast.makeText(
//                                            CheckInstruction.this,
//                                            "该病人不存在！", Toast.LENGTH_LONG);
//                                    tt.show();
//                                    tt.setGravity(Gravity.CENTER, 0, 0);
                                }
                            } catch (InstantiationException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                    } else {
                        // 扫医嘱
                        if (BAR_value.length() >= 7) {
                            // 先判断是否是本人的医嘱，非本人医嘱则先跳到扫描病人医嘱的界面
                            InPatient ip = new InPatient();
                            Map<String, String> map = new HashMap<String, String>();
                            map.put("hiszyxh", BAR_value);
                            try {
                                JSONArray pInfoArray = WSHelper.getWebserviceFun("GetPatientInfoByHiszyxh", map);
                                if (pInfoArray != null) {
                                    ip.getValue(pInfoArray.getJSONObject(0));
                                }
                                if (pi.BAH != null && !(pi.BAH.equals(ip.BAH))) {
                                    Intent newintent = new Intent(getApplicationContext(), CheckInstruction.class);
                                    newintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    newintent.putExtra("patientinfo", ip);
                                    newintent.putExtra("userinfo", usr);
                                    newintent.putExtra("ly", "2");
                                    startActivity(newintent);
                                    return;
                                }else {
                                    // 是本人的医嘱则开始执行
                                    showAdvoceDialog(BAR_value);
                                }
                            } catch (Exception e) {
                                Toast tt = Toast.makeText(CheckInstruction.this, "获取病人信息失败！", Toast.LENGTH_LONG);
                                tt.show();
                            }
                        }
                    }

                } else {
                    Toast tt = Toast.makeText(CheckInstruction.this,
                            "扫描出错！", Toast.LENGTH_LONG);
                    tt.show();
                    tt.setGravity(Gravity.CENTER, 0, 0);
                }
            }

        };
    }

    /**
     * 绑定时间
     */
    private void bandList() {
        tv_Syzs.setText("0");
        tv_Yzzxts.setText("0");
        tv_Yzsyts.setText("0");
        slvYz.setAdapter(null);
        if (jsonArray != null) {
            JSONArray newItems = new JSONArray();
        }

        if (jsonArray != null) {

            adapter = new CheckInstructionItemAdapter(CheckInstruction.this,
                    jsonArray);

            tv_Syzs.setText(String.valueOf(jsonArray.length()));

            slvYz.setAdapter(adapter);
            slvYz.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    // TODO Auto-generated method stub
                    JSONObject yzObj = null;

                    try {
                        yzObj = jsonArray.getJSONObject(position);
                        JSONArray value = yzObj.getJSONArray("value");
                        String key = yzObj.getString("key");
                        if("kfyw".equals(key)){
                            return;
                        }
                        if (value != null) {
                            JSONObject o = value.getJSONObject(0);
                            if(o != null){
                                strJlxh = o.getString("YPBQTM");
                                strYzmc = o.getString("ORDER_NAME");
                                showAdvoceDialog(strJlxh);
                            }
                        }



                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

//
                }

            });

        }
    }

    public void showAdvoceDialog(String ywtm) {
        mDialog = new MultiDialog(CheckInstruction.this,
                MultiDialog.DialogType.FourButton);
        mDialog.setMessage("您是否要执行此医嘱?");
        mDialog.setbtn3Text("确定");
        mDialog.setbtn4Text("取消");
        mDialog.setBtn3Listener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mDialog.cancel();
                exeAdvice(ywtm);// 执行医嘱
            }
        });
        mDialog.setBtn4Listener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mDialog.cancel();
            }
        });

        mDialog.show();
    }



    //    PDA扫码执行医嘱
    private void exeAdvice(String jlxh) {
        Map<String, String> map = new HashMap<>();
        map.put("ywbqtm", jlxh);
        map.put("emrzyxh", !TextUtils.isEmpty(pi.BAH) ? pi.BAH : pi.HISZYXH);
        map.put("usercode", usr.GH);
        LogListActivity.logList.add("执行医嘱传参->"+" ywbqtm ="+jlxh+" emrzyxh ="+pi.BAH+" usercode:"+usr.GH);
        String pdaDocOrderInfoOp = WSHelper.exeAdvice("PDADocOrderInfoOp", map);
        vibrator();
        if (!TextUtils.isEmpty(pdaDocOrderInfoOp)) {
            Toast.makeText(this, pdaDocOrderInfoOp, Toast.LENGTH_SHORT).show();
        }
        LogListActivity.logList.add("执行医嘱接口响应->"+pdaDocOrderInfoOp);
    }

    public void vibrator(){
        Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
        long [] pattern = {50,100,50,100};   // 停止 开启 停止 开启
        vibrator.vibrate(pattern,-1);
    }


    /**
     * 执行医嘱声音
     */
    private void runRingError() {
        SoundPool soundPool = new SoundPool(100, AudioManager.STREAM_MUSIC, 1);
        soundPool.load(this, R.raw.error, 1);
        soundPool
                .setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                    @Override
                    public void onLoadComplete(SoundPool soundPool, int i,
                                               int i2) {
                        soundPool.play(1, // 声音id
                                1, // 左声道
                                1, // 右声道
                                1, // 优先级
                                0, // 0表示不循环，-1表示循环播放
                                1);// 播放比率，0.5~2，一般为1
                    }
                });
    }

    static class MyHandler extends Handler {
        WeakReference<CheckInstruction> mActivityReference;

        MyHandler(CheckInstruction checkInstruction) {
            mActivityReference = new WeakReference<CheckInstruction>(
                    checkInstruction);
        }

        public void handleMessage(Message msg) {
            final CheckInstruction activity = mActivityReference.get();

            switch (msg.what) {
                case 1:
                    activity.readInstruction();
                    activity.bandList();

                    break;
            }
            super.handleMessage(msg);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // handler.removeCallbacks(myRunnable);
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onPause()
     */
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        CheckInstruction.this.unregisterReceiver(checkInstructionReciever);
        super.onPause();
    }

    /*
     * @see android.app.Activity#onRestart()
     */
    @Override
    protected void onRestart() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BAR_READ_ACTION);
        filter.addAction(RFID_READ_ACTION);
        filter.addAction(INTENT_ACTION_SCAN_RESULT);
        filter.addAction(SCANACTION);
        filter.addAction(Neusoft);
        filter.addAction(NLSCAN_SCANNER);
        registerReceiver(checkInstructionReciever, filter);
        super.onRestart();
    }

    /*
     * (non-Javadoc)
     *
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BAR_READ_ACTION);
        filter.addAction(RFID_READ_ACTION);
        filter.addAction(INTENT_ACTION_SCAN_RESULT);
        filter.addAction(SCANACTION);
        filter.addAction(Neusoft);
        filter.addAction(NLSCAN_SCANNER);
        registerReceiver(checkInstructionReciever, filter);
        super.onResume();
    }

}
